package com.heima.search.service.impl;

import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    BehaviorFeign behaviorFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 删除搜索历史
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //3 查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (behaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //4 执行删除
        mongoTemplate.remove(
                Query.query(Criteria.where("id").is(dto.getHistoryId()).and("entryId").is(behaviorEntry.getId())),
                ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //3 查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        if (user != null) {
            ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
            if (behaviorEntry != null) {
                List<ApUserSearch> searchList = mongoTemplate
                        .find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                        .with(Sort.by(Sort.Order.desc("createdTime"))), ApUserSearch.class);
                return ResponseResult.okResult(searchList);
            }
        }

        return ResponseResult.okResult(new ArrayList<>());
    }


    /**
     * 保存用户搜索历史记录
     * 方法二： 遍历集合
     * @param dto
     */
    @Override
    @Async  // 开启异步
    public void insert(UserSearchDto dto) {

        //1 参数校验
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            log.error("SearchWords is null");
            return;
        }

        //2 获取登录用户信息
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser != null) {
            //3 查询行为实体
            ApBehaviorEntry behaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(apUser.getId(),
                    dto.getEquipmentId());
            if (behaviorEntry != null) {

                //4 查询当前用户的历史记录 Mongo
                List<ApUserSearch> searchList = mongoTemplate.find(
                        Query.query(Criteria
                                .where("entryId").is(behaviorEntry.getId()))
                                .with(Sort.by(Sort.Order.desc("createdTime")))
                        ,
                        ApUserSearch.class);

                ApUserSearch apUserSearch = new ApUserSearch();
                apUserSearch.setCreatedTime(new Date());
                apUserSearch.setEntryId(behaviorEntry.getId());
                apUserSearch.setKeyword(dto.getSearchWords());

                // 无历史记录
                if (searchList == null || searchList.size() == 0) {
                    mongoTemplate.save(apUserSearch);
                    return;
                }

                //5 查询是否存在当前历史记录
//                boolean flag = searchList.stream().anyMatch(x -> x.getKeyword().equals(dto.getSearchWords()));
//                if (flag) {
//                    //5.1 存在，更新时间
//                    mongoTemplate.findOne()
//                }else {
//                    //5.2 不存在（当前用户的历史记录总条数是否大于10）
//                }
                for (ApUserSearch userSearch : searchList) {
                    if (userSearch.getKeyword().equals(dto.getSearchWords())) {
                        //5.1 存在，更新时间
                        userSearch.setCreatedTime(new Date());
                        mongoTemplate.save(userSearch);
                        return;
                    }
                }

                // 不存在
                if (searchList.size() < 10) {
                    mongoTemplate.save(apUserSearch);
                }else {
                    ApUserSearch lastUserSearch = searchList.get(searchList.size() - 1);
                    mongoTemplate.findAndReplace(
                            Query.query(Criteria.where("id").is(lastUserSearch.getId())), apUserSearch);
                }

            }

        }
    }
}
